use crate::std_extensions::primitive::ExtendSlice;
use std::alloc::{alloc, dealloc, handle_alloc_error, realloc, Layout};
use std::marker::PhantomData;
use std::ops::{Deref, DerefMut};
use std::option::Option::Some;
use std::{mem, ptr as pointer};

struct MyUnique<T: ?Sized> {
  ptr: *const T,
  _marker: PhantomData<T>,
}

unsafe impl<T: Send + ?Sized> Send for MyUnique<T> {}

unsafe impl<T: Sync + ?Sized> Sync for MyUnique<T> {}

impl<T: ?Sized> Copy for MyUnique<T> {}

impl<T: ?Sized> Clone for MyUnique<T> {
  #[inline]
  fn clone(&self) -> Self {
    *self
  }
}

impl<T: ?Sized> MyUnique<T> {
  #[inline]
  pub unsafe fn as_ref(&self) -> &T {
    &*self.as_ptr()
  }

  #[inline]
  pub fn new(ptr: *mut T) -> Option<Self> {
    if !ptr.is_null() {
      Some(unsafe {
        MyUnique {
          ptr: ptr as _,
          _marker: PhantomData,
        }
      })
    } else {
      None
    }
  }

  #[inline]
  pub const fn as_ptr(&self) -> *mut T {
    self.ptr as *mut T
  }

  #[inline]
  pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
    MyUnique {
      ptr: ptr as _,
      _marker: PhantomData,
    }
  }

  #[inline]
  pub unsafe fn as_mut(&mut self) -> &mut T {
    &mut *self.as_ptr()
  }
}

impl<T> MyUnique<T> {
  pub const fn empty() -> Self {
    unsafe { MyUnique::new_unchecked(mem::align_of::<T>() as *mut T) }
  }
}

pub struct MyVec<T> {
  buf: RawVec<T>,
  len: usize,
}

impl<T: Clone> Clone for MyVec<T> {
  fn clone(&self) -> MyVec<T> {
    <[T]>::to_my_vec(&**self)
  }
}

impl<T> MyVec<T> {
  pub fn new() -> Self {
    MyVec {
      buf: RawVec::new(),
      len: 0,
    }
  }

  pub fn with_capacity(capacity: usize) -> MyVec<T> {
    MyVec {
      buf: RawVec::with_capacity(capacity),
      len: 0,
    }
  }

  fn ptr(&self) -> *mut T {
    self.buf.ptr.as_ptr()
  }

  fn cap(&self) -> usize {
    self.buf.cap
  }
}

impl<T> MyVec<T> {
  pub fn push(&mut self, element: T) {
    if self.len == self.cap() {
      self.buf.grow();
    }
    unsafe {
      pointer::write(self.ptr().add(self.len), element);
    }
    self.len += 1;
  }

  pub fn pop(&mut self) -> Option<T> {
    if self.len == 0 {
      None
    } else {
      self.len -= 1;
      unsafe { Some(pointer::read(self.ptr().add(self.len))) }
    }
  }

  pub fn insert(&mut self, index: usize, element: T) {
    assert!(index <= self.len, "index out of bounds");
    if self.cap() == self.len {
      self.buf.grow();
    }
    unsafe {
      if index < self.len {
        pointer::copy(self.ptr().add(index), self.ptr().add(index + 1), self.len - index);
      }
      pointer::write(self.ptr().add(index), element);
      self.len += 1;
    }
  }

  pub fn remove(&mut self, index: usize) -> T {
    assert!(index < self.len, "index out of bounds");
    unsafe {
      self.len -= 1;
      let result = pointer::read(self.ptr().add(index));
      pointer::copy(self.ptr().add(index + 1), self.ptr().add(index), self.len - index);
      result
    }
  }
}

impl<T> Deref for MyVec<T> {
  type Target = [T];

  fn deref(&self) -> &[T] {
    unsafe { std::slice::from_raw_parts(self.ptr(), self.len) }
  }
}

impl<T> DerefMut for MyVec<T> {
  fn deref_mut(&mut self) -> &mut [T] {
    unsafe { std::slice::from_raw_parts_mut(self.ptr(), self.len) }
  }
}

impl<T> MyVec<T> {
  fn into_iter(self) -> IntoIter<T> {
    unsafe {
      let iter = RawValIter::new(&self);
      let buf = pointer::read(&self.buf);
      mem::forget(self);

      IntoIter { iter, _buf: buf }
    }
  }
}

struct IntoIter<T> {
  _buf: RawVec<T>,
  iter: RawValIter<T>,
}

impl<T> Drop for MyVec<T> {
  fn drop(&mut self) {
    while let Some(_) = self.pop() {}
  }
}

impl<T> Iterator for IntoIter<T> {
  type Item = T;
  fn next(&mut self) -> Option<T> {
    self.iter.next()
  }

  fn size_hint(&self) -> (usize, Option<usize>) {
    self.iter.size_hint()
  }
}

impl<T> DoubleEndedIterator for IntoIter<T> {
  fn next_back(&mut self) -> Option<T> {
    self.iter.next_back()
  }
}

impl<T> Drop for IntoIter<T> {
  fn drop(&mut self) {
    for _ in &mut self.iter {}
  }
}

struct RawVec<T> {
  ptr: MyUnique<T>,
  cap: usize,
}

impl<T> RawVec<T> {
  fn new() -> Self {
    let cap = if mem::size_of::<T>() == 0 { !0 } else { 0 };
    RawVec {
      ptr: MyUnique::empty(),
      cap,
    }
  }

  pub fn with_capacity(cap: usize) -> Self {
    RawVec::allocate_in(cap, None)
  }

  fn allocate_in(cap: usize, p: Option<MyUnique<T>>) -> Self {
    unsafe {
      let elem_size = mem::size_of::<T>();
      assert_ne!(elem_size, 0, "capacity overflow");

      let (new_cap, ptr) = if cap == 0 {
        let ptr = alloc(Layout::array::<T>(1).unwrap());
        (1, ptr)
      } else {
        if let Some(some_p) = p {
          let new_cap = cap * 2;
          let layout = Layout::array::<T>(cap).unwrap();
          let ptr = realloc(some_p.as_ptr() as *mut _, layout, layout.size());
          (new_cap, ptr)
        } else {
          let ptr = alloc(Layout::array::<T>(cap).unwrap());
          (cap, ptr)
        }
      };

      if ptr.is_null() {
        handle_alloc_error(Layout::from_size_align_unchecked(
          new_cap * elem_size,
          mem::align_of::<T>(),
        ));
      }

      Self {
        ptr: MyUnique::new_unchecked(ptr as *mut _),
        cap: new_cap,
      }
    }
  }

  fn grow(&self) -> Self {
    RawVec::allocate_in(self.cap, Some(self.ptr))
  }
}

impl<T> Drop for RawVec<T> {
  fn drop(&mut self) {
    let elem_size = mem::size_of::<T>();
    if self.cap != 0 && elem_size != 0 {
      unsafe {
        dealloc(
          self.ptr.as_ptr() as *mut _,
          Layout::from_size_align_unchecked(self.cap * elem_size, mem::align_of::<T>()),
        );
      }
    }
  }
}

struct RawValIter<T> {
  start: *const T,
  end: *const T,
}

impl<T> RawValIter<T> {
  unsafe fn new(slice: &[T]) -> Self {
    RawValIter {
      start: slice.as_ptr(),
      end: if mem::size_of::<T>() == 0 {
        ((slice.as_ptr() as usize) + slice.len()) as *const _
      } else if slice.len() == 0 {
        slice.as_ptr()
      } else {
        slice.as_ptr().offset(slice.len() as isize)
      },
    }
  }
}

impl<T> Iterator for RawValIter<T> {
  type Item = T;

  fn next(&mut self) -> Option<T> {
    if self.start == self.end {
      None
    } else {
      unsafe {
        let result = pointer::read(self.start);
        self.start = if mem::size_of::<T>() == 0 {
          (self.start as usize + 1) as *const _
        } else {
          self.start.offset(1)
        };
        Some(result)
      }
    }
  }

  fn size_hint(&self) -> (usize, Option<usize>) {
    let elem_size = mem::size_of::<T>();
    let len = (self.end as usize - self.start as usize) / (if elem_size == 0 { 1 } else { elem_size });
    (len, Some(len))
  }
}

impl<T> DoubleEndedIterator for RawValIter<T> {
  fn next_back(&mut self) -> Option<T> {
    if self.start == self.end {
      None
    } else {
      unsafe {
        self.end = if mem::size_of::<T>() == 0 {
          (self.end as usize - 1) as *const _
        } else {
          self.end.offset(-1)
        };
        Some(pointer::read(self.end))
      }
    }
  }
}

pub mod my_vec_test {
  use super::*;

  #[test]
  fn create_push_pop() {
    let mut v = MyVec::new();
    v.push(1);
    assert_eq!(1, v.len());
    assert_eq!(1, v[0]);
    for i in v.iter_mut() {
      *i += 1;
    }
    v.insert(0, 5);
    let x = v.pop();
    assert_eq!(Some(2), x);
    assert_eq!(1, v.len());
    v.push(10);
    let x = v.remove(0);
    assert_eq!(5, x);
    assert_eq!(1, v.len());
  }

  #[test]
  pub fn create_by_capacity() {
    let mut v = MyVec::with_capacity(10);
    v.push(10);
    assert_eq!(v.pop(), Some(10));
  }

  #[test]
  pub fn iter_test() {
    let mut v = MyVec::new();
    for i in 0..10 {
      v.push(Box::new(i))
    }
    let mut iter = v.into_iter();
    let first = iter.next().unwrap();
    let last = iter.next_back().unwrap();
    drop(iter);
    assert_eq!(0, *first);
    assert_eq!(9, *last);
  }

  #[test]
  pub fn test_zst() {
    let mut v = MyVec::new();
    for _i in 0..10 {
      v.push(())
    }
    let mut count = 0;
    for _ in v.into_iter() {
      count += 1
    }
    assert_eq!(10, count);
  }
}
